import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

public class RemoteSubject extends UnicastRemoteObject implements RemoteSubjectInterface  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8899877048512933851L;

	private ArrayList<String> observers;
	
	private ArrayList<RemoteObserverInterface> obs;
	
	private Document doc = null;
	
	protected RemoteSubject() throws RemoteException {
		super();
		this.observers = new ArrayList<String>();
		this.obs = new ArrayList<RemoteObserverInterface>();
		
		
	}

	@Override
	public void Attach(String obs) throws RemoteException {
		
		/*if(this.observers.contains(obs)) {
			System.out.println("A cliente tried to register with an name already in use: "+obs);
			return;
		}*/
		
		this.observers.add(obs);

		
		
		System.setSecurityManager(new RMISecurityManager());
		
		try {
			   
		    RemoteObserverInterface client;

		    // Get reference to remote object
		    System.out.println("Lookingup name: " + obs);
		    client = (RemoteObserverInterface) Naming.lookup(obs);
		    
		    if(client == null) {
		    	System.out.println("Failed to get client handle");
		    	
		    	return;
		    }
		    
		    System.out.println("Got handle to the "+obs+" client observer");
		    
		    this.obs.add(client);
		    
		    
		    
		} catch (Exception e) {
		    System.out.println("Server observer exception: " 
				       + e.getMessage());
		    e.printStackTrace();
		}	
		
		
		
		System.out.println("Client "+obs+" joinned the drawing!");
		
		System.out.println("Now participating:");
		for (String ob : this.observers) {
			System.out.println(ob+";");
		}
		
		
		
		
		//Notify();
	}

	@Override
	public void Detach(String obs) throws RemoteException {
		this.obs.remove(this.observers.indexOf(obs));
		this.observers.remove(obs);
		System.out.println(obs+" has left the drawing");
		
		
		
	}

	@Override
	public void Notify() throws RemoteException {
		//this.doc = "All welcome "+observers.get(observers.size()-1).toString()+" to the party!!";
		
		for (RemoteObserverInterface obs : this.obs) {
			obs.Update(this);
		}
		
	}

	@Override
	public Document getDoc() throws RemoteException {
		return this.doc;
	}

	@Override
	public void setDoc(Document doc) throws RemoteException {
		this.doc = doc;
		Notify();
		
	}

}
